﻿namespace eg_077_索引器
{
    internal class Program
    {
        class Result
        {
            int[] sorces;

            public Result(params int[] sorces)
            {
                this.sorces = sorces;
            }
            // 学科分数索引器
            // 索引器没有名称，用关键词 this 替代.
            public int this[int index]
            {
                get { return sorces[index]; }
                set { sorces[index] = value; }
            }
            public int Count { get { return sorces.Length; } }
        }

        class StudentGPA
        {
            Result[] results;
            public StudentGPA(Result[] results) { this.results = results; } // 构造函数
            // 索引器
            public double this[int grade]
            {
                get
                {
                    Result result = results[grade - 1];
                    if (grade < 1 || grade > 4 || result == null) return -1;
                    int sum = 0;
                    for (int i = 0; i < results.Length; i++) { sum += result[i]; }
                    return (double)sum / result.Count;
                }
            }
        }
        static void Main(string[] args)
        {
            Result[] results = new Result[4];
            results[0] = new Result(86, 75, 98, 62, 76);            //一年级成绩表
            results[1] = new Result(96, 84, 88, 59);                //二年级成绩表
            results[2] = new Result(76, 65, 68, 67, 86);            //三年级成绩表
            results[3] = new Result(56, 93, 48, 52, 77, 88);        //四年级成绩表
            StudentGPA gpa = new StudentGPA(results);               //实例化年级的平均成绩类
                                                                    //输出各年级的平均成绩
            for (int i = 1; i < 5; i++) Console.WriteLine("{0}年级平均成绩为：{1}", i, gpa[i]);
        }
    }
}